package com.example.springbootvuetest.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.springbootvuetest.mapper.AddressMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootvuetest.base.Result;
import lombok.RequiredArgsConstructor;
import com.example.springbootvuetest.entity.Address;
import com.example.springbootvuetest.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * <p>
 * controller
 * </p>
 *
 * @author shuoye
 * @since 2023-03-14
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(tags = "REST - ")
@RestController
@RequestMapping("/address")
public class AddressController {
    private final IAddressService service;
    private final AddressMapper addressMapper;

    @PostMapping("/add")
    @ApiOperation(value = "新增")
    public Result createOne(@RequestBody Address entity) {
        Boolean defaultFlag = entity.getDefaultFlag();
        if (defaultFlag) {
            addressMapper.updateDefaultAddress(entity.getUserId());
        }
        boolean flag = service.save(entity);
        return flag ? Result.success() : Result.error();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改地址")
    public Result updateAddress(@RequestBody Address entity) {
        Boolean defaultFlag = entity.getDefaultFlag();
        if (defaultFlag) {
            addressMapper.updateDefaultAddress(entity.getUserId());
        }
        boolean flag = service.updateById(entity);
        return flag ? Result.success() : Result.error();
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除")
    public Result delete(@RequestParam("id") Integer id) {
        boolean flag = service.removeById(id);
        return flag ? Result.success() : Result.error();
    }

    @GetMapping("/info")
    @ApiOperation(value = "地址查询")
    public Result queryAddress(@RequestParam(name = "userId") Integer userId) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<Address>();
        queryWrapper.eq("user_id", userId);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        return Result.success(addresses);
    }
}